﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TdolDemo_QBZ.Models.Task;
using TdolDemo_QBZ.Models;

namespace TdolDemo_QBZ.Repository
{
    public class TdolTaskListRepository : ITdolTaskListRepository
    {
        //get list
        public List<TaskModel> GetTaskList(int taskId)
        {
            var tasks = new List<TaskModel>();
            var db = new sqltestContext();
            tasks = db.TbTdolTaskList
                    .Where(s =>s.IsDelete == 0 && (taskId == 0 || s.TaskId == taskId))
                    .Select(s => new TaskModel { TaskId = s.TaskId, Description = s.Description, OpenIntervalStart = s.OpenIntervalStart, OpenIntervalEnd = s.OpenIntervalEnd, RegionId = s.RegionId, Status = s.Status, TestDateId = s.TestDateId, Remarks = s.Remarks,CreateBy=s.CreateBy,CreateOn=s.CreateOn,Guid=s.Guid,IsDelete= s.IsDelete,TimeStamp = s.TimeStamp,UpdateBy =s.UpdateBy,UpdateOn =s.UpdateOn })
                    .ToList();
            return tasks;
        }
        //add
        public int AddTaskList(TaskModel task)
        {
            var db = new sqltestContext();
            var dbtask = new TbTdolTaskList {
                CreateBy = task.CreateBy,
                CreateOn = task.CreateOn,
                Description = task.Description,
                Guid = task.Guid,
                IsDelete = task.IsDelete,
                OpenIntervalEnd = task.OpenIntervalEnd,
                OpenIntervalStart = task.OpenIntervalStart,
                RegionId = task.RegionId,
                Remarks = task.Remarks,
                Status = task.Status,
                TestDateId = task.TestDateId
            };
            db.TbTdolTaskList.Add(dbtask);
            if (db.SaveChanges() > 0)
            {
                return dbtask.TaskId;
            }
            else
            {
                return 0;
            }
            
        }
        //delate
        public int DelateTaskList(int taskId)
        {
            var db = new sqltestContext();
            var task = db.TbTdolTaskList.Where(s => s.TaskId == taskId).FirstOrDefault();
            /*
            db.Entry(task).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            db.Remove(task);
            db.RemoveRange(db.TbTdolTaskUnits.Where(s => s.TaskId == taskId).ToList());
            */
            if(task!=null && task.TaskId > 0)
            {
                task.IsDelete = 1;
            }
            return db.SaveChanges();
        }
    }
}
